package com.jmu.bishe.web.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.jasper.tagplugins.jstl.core.Url;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * <pre>
 * <b><font color="blue">SystemInterceptor</font></b>
 * </pre>
 * 
 * <pre>
 * <b>&nbsp;--系统拦截器--</b>
 * </pre>
 * 
 * <pre></pre>
 * 
 * JDK版本：JDK1.5.0
 * 
 * @author <b>ulyn</b>
 */
@Component("systemInterceptor")  
@Repository
public class SystemInterceptor extends HandlerInterceptorAdapter {

	/**
	 * 在Controller方法前进行拦截 如果返回false 从当前拦截器往回执行所有拦截器的afterCompletion方法,再退出拦截器链.
	 * 如果返回true 执行下一个拦截器,直到所有拦截器都执行完毕. 再运行被拦截的Controller.
	 * 然后进入拦截器链,从最后一个拦截器往回运行所有拦截器的postHandle方法.
	 * 接着依旧是从最后一个拦截器往回执行所有拦截器的afterCompletion方法.
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

        request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		String uri = request.getRequestURI();
		System.out.println("SystemInterceptor拦截到请求："+uri);
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		//判断拦截的请求路径 uri.indexOf("background") != -1
		
		if(uri.toLowerCase().indexOf("/admin/")!=-1){
			//属于访问需要验证登录权限的
			Object obj = request.getSession().getAttribute("user");
			if (null == obj) {
				// 未登录并且是不看
				StringBuilder builder = new StringBuilder();
				builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
				builder.append("alert('您还没有登陆或者页面过期，请重新登录');");
				builder.append("top.location.href='");
				builder.append(basePath);
				String url = URLEncoder.encode(uri.replaceFirst(path,""),"utf-8");
				builder.append("login.do?redirectUrl="+url+"';</script>");
				printWriter(response,builder.toString());
				return false;
			}
		}
		return super.preHandle(request, response, handler);
	}

	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
//
//		if (modelAndView != null) {
//			String viewName = modelAndView.getViewName();
//		//	System.out.println("view name : " + viewName);
//		} else {
//		//	System.out.println("view null ");
//		}
		request.setAttribute("requestContrlURI", request.getRequestURI());
	}

	/**
	 * 在Controller方法后进行拦截 当有拦截器抛出异常时,会从当前拦截器往回执行所有拦截器的afterCompletion方法
	 */
	@Override
	public void afterCompletion(HttpServletRequest httpservletrequest,
			HttpServletResponse httpservletresponse, Object obj,
			Exception exception) throws Exception {

	}
	private void printWriter(HttpServletResponse response,String str){
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(str);
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(out!=null){
				out.close();
			}
		}
		
	}
}